﻿using System;
using System.Drawing;

namespace LOGISTCBUS.Entities
{
    public class GeneralHelpers
    {
        public static void ResizeImage(String originalFile, String newFile, Int32 newWidth, Int32 maxHeight, Boolean onlyResizeIfWider)
        {
            var fullsizeImage = Image.FromFile(originalFile);

            //prevent using images internal thumbnail
            fullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
            fullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);

            if (onlyResizeIfWider)
            {
                if (fullsizeImage.Width <= newWidth)
                {
                    newWidth = fullsizeImage.Width;
                }
            }

            var newHeight = fullsizeImage.Height * newWidth / fullsizeImage.Width;
            if (newHeight > maxHeight)
            {
                //resize with height instead
                newWidth = fullsizeImage.Width * maxHeight / fullsizeImage.Height;
                newHeight = maxHeight;
            }

            var newImage = fullsizeImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);

            //clear handle to original file so that we can overwrite it if necessary
            fullsizeImage.Dispose();

            //save resized picture
            newImage.Save(newFile);
        }
    }
}
